from PIL import Image
from PIL import ImageDraw
import sys
import json
import os
import numpy as np
import csv

# TODO 给定一个路径，将一个路径里的文件名全部放到一个list中

def eachFile(filepath):  # 获得指定文件夹里的所有文件名
    pathDir = os.listdir(filepath)
    filelist = []
    for allDir in pathDir:
        child = os.path.join('%s%s' % (filepath, allDir))
        filelist.append(child)
    return filelist


# TODO 在一堆文件名list中，挑出所有后缀为json的文件

def chooseFile(filelist):  # 挑出里面的json文件
    reslist = []
    for filename in filelist:
        if(filename[-4:] == 'json'):
            reslist.append(filename)
    return reslist


filename = "./dataset/"  # 数据集路径
jslist = chooseFile(eachFile(filename))  # 得到数据集路径中的所有json文件
picnum = 1

# TODO 写csv
outCsv = open("./outcsv.csv", "w", encoding='utf-8')
csv_writer = csv.writer(outCsv)
csv_writer.writerow(["num", "filename", "shape", "all_pixs",
                    "area1_pixs", "area2_pixs", "area1/area2"])


isShow = sys.argv[1]

print()
print("----------批处理程序----------\n")
print("# 数据集路径：[", filename, "]")
print("# 文件数目：[", len(jslist), "] 个")
print("# 开始批处理...\n")

# 批处理
for jsFile in jslist:
    # TODO 读json文件
    with open(jsFile) as f:  # 打开json文件
        image_info = json.load(f)

    image_height = image_info['imageHeight']  # 图片高度
    image_width = image_info['imageWidth']  # 图片宽度
    shape_list = image_info['shapes']  # 所有的形状
    thisPath = image_info['imagePath']  # 图片路径
    all_pixs = image_width*image_height  # 整张图片的像素数
    area1_dict = {}  # 小区域字典{形状:大小}
    area2_dict = {}  # 大区域字典{形状:大小}

    # 处理每一个形状
    for shape in shape_list:
        shape_label = shape['label']  # 形状标签
        point_list = shape['points']  # 形状轮廓点集合

        # 转换轮廓点集合的数据格式 -- 绘制多边形的时候需要tuple -- ((),(),...,())
        point_tuple = ()
        for e in point_list:
            point_tuple = point_tuple + tuple(e)

        # TODO 新建和图片一样大的画布并用点集绘制多边形
        new_img = Image.new('L', (image_width, image_height), 0)
        draw_board = ImageDraw.Draw(new_img)
        draw_board.polygon(point_tuple, fill="white")  # 用标注点画出多边形，并将内部填充

        # 显示图片（可选）
        if(isShow == '2'):
            new_img.show()

        # TODO 转成np.array来计数
        img_L = np.array(new_img.convert("L"))  # 转为np.array
        count = np.where(img_L == 255)[0].shape[0]

        # 同一目标的小区域标注末尾有'*'
        if(shape_label[-1] == '*'):
            area1_dict[shape_label[:-1]] = count
        else:
            area2_dict[shape_label] = count

    # 一组一组的放入
    for lab in area1_dict:
        csv_writer.writerow([picnum, thisPath, lab, all_pixs, area1_dict[lab],
                            area2_dict[lab], area1_dict[lab]/area2_dict[lab]])
        picnum += 1

print("# 处理完成！\n")
print("-----------------------------")
